package com.mall.service;

import com.mall.pojo.Order;
import com.mall.pojo.OrderItem;
import com.mall.pojo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Autowired
    private CartService cartService;
    
    /**
     * 创建订单
     */
    @Transactional
    public Order createOrder(Long userId, Long addressId, Integer deliveryTimeType, 
                           Integer payType, Integer payChannel, String buyerMessage, 
                           List<Map<String, Object>> goodsList) {
        try {
            // 1. 计算订单金额
            BigDecimal totalPrice = BigDecimal.ZERO;
            for (Map<String, Object> item : goodsList) {
                BigDecimal price = BigDecimal.valueOf(((Number)item.get("price")).doubleValue());
                Integer count = (Integer)item.get("count");
                BigDecimal itemTotal = price.multiply(BigDecimal.valueOf(count));
                totalPrice = totalPrice.add(itemTotal);
            }
            
            BigDecimal postFee = new BigDecimal("10.00"); // 固定运费
            BigDecimal payMoney = totalPrice.add(postFee);
            
            // 2. 创建订单
            LocalDateTime now = LocalDateTime.now();
            
            jdbcTemplate.update(
                "INSERT INTO orders (user_id, state, payMoney, postFee, create_time, countdown) " +
                "VALUES (?, ?, ?, ?, ?, ?)",
                userId, 1, payMoney, postFee, now, 15 * 60);
            
            Long orderId = jdbcTemplate.queryForObject(
                "SELECT LAST_INSERT_ID()", Long.class);
                
            // 3. 创建订单项
            for (Map<String, Object> item : goodsList) {
                Long skuId = ((Number)item.get("sku_id")).longValue();
                String name = (String)item.get("name");
                String image = (String)item.get("image");
                Integer count = (Integer)item.get("count");
                BigDecimal price = BigDecimal.valueOf(((Number)item.get("price")).doubleValue());
                
                jdbcTemplate.update(
                    "INSERT INTO order_item (order_id, sku_id, name, image, real_pay, quantity) " +
                    "VALUES (?, ?, ?, ?, ?, ?)",
                    orderId, skuId, name, image, price, count);
            }
            
            // 4. 清空购物车中已下单的商品
            jdbcTemplate.update(
                "DELETE FROM cart WHERE user_id = ? AND checked = 1",
                userId);
            
            // 5. 返回订单信息
            Order order = new Order();
            order.setId(orderId);
            order.setUserId(userId);
            order.setState(1);
            order.setPayMoney(payMoney);
            order.setPostFee(postFee);
            order.setCreateTime(now);
            order.setCountdown(15 * 60);
            
            return order;
        } catch (Exception e) {
            throw new RuntimeException("创建订单失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 获取订单详情
     */
    public Order getOrderDetail(Long orderId, Long userId) {
        try {
            // 1. 查询订单基本信息
            Map<String, Object> orderMap = jdbcTemplate.queryForMap(
                "SELECT * FROM orders WHERE id = ? AND user_id = ?", 
                orderId, userId);
            
            if (orderMap == null || orderMap.isEmpty()) {
                return null;
            }
            
            // 2. 构建订单对象
            Order order = new Order();
            order.setId(((Number)orderMap.get("id")).longValue());
            order.setUserId(((Number)orderMap.get("user_id")).longValue());
            order.setState((Integer)orderMap.get("state"));
            order.setPayMoney(new BigDecimal(orderMap.get("payMoney").toString()));
            order.setPostFee(new BigDecimal(orderMap.get("postFee").toString()));
            order.setCreateTime((LocalDateTime)orderMap.get("create_time"));
            order.setCountdown((Integer)orderMap.get("countdown"));
            
            // 3. 查询订单项
            List<Map<String, Object>> orderItems = jdbcTemplate.queryForList(
                "SELECT * FROM order_item WHERE order_id = ?", orderId);
            
            List<OrderItem> items = new ArrayList<>();
            for (Map<String, Object> item : orderItems) {
                OrderItem orderItem = new OrderItem();
                orderItem.setId(((Number)item.get("id")).longValue());
                orderItem.setOrderId(((Number)item.get("order_id")).longValue());
                orderItem.setSkuId(((Number)item.get("sku_id")).longValue());
                orderItem.setName((String)item.get("name"));
                orderItem.setImage((String)item.get("image"));
                orderItem.setAttrsText((String)item.get("attrs_text"));
                orderItem.setRealPay(new BigDecimal(item.get("real_pay").toString()));
                orderItem.setQuantity((Integer)item.get("quantity"));
                
                items.add(orderItem);
            }
            
            order.setOrderItems(items);
            
            return order;
        } catch (Exception e) {
            throw new RuntimeException("获取订单详情失败: " + e.getMessage(), e);
        }
    }
    
    /**
     * 支付订单
     */
    public boolean payOrder(Long orderId, Long userId) {
        try {
            // 更新订单状态为待发货
            int rows = jdbcTemplate.update(
                "UPDATE orders SET state = 2 WHERE id = ? AND user_id = ?",
                orderId, userId);
                
            return rows > 0;
        } catch (Exception e) {
            throw new RuntimeException("支付订单失败: " + e.getMessage(), e);
        }
    }
} 